package ruifight.member.wxController;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fasterxml.jackson.databind.JsonNode;

import ruifight.member.model.UserInfo;
import ruifight.member.model.UserInfoExample;
import ruifight.member.service.UserInfoService;
import ruifight.member.util.CommonUtil;
import ruifight.member.util.HttpClientUtil;
import ruifight.member.util.JsonUtils;
import ruifight.member.util.MD5Util;


@Controller
@RequestMapping("/wxgzh/")
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
	@Resource
	private UserInfoService userInfoService;
	@RequestMapping("/loginInit")
	public String login(){
		
		return "login";
	}
	@RequestMapping("/login")
	public String login(UserInfo userInfo,HttpServletRequest request, HttpServletResponse response, Model model){
		try{
			UserInfoExample userInfoExample=new UserInfoExample();
			userInfoExample.createCriteria()
				.andLoginNameEqualTo(userInfo.getLoginName())
				.andPasswordEqualTo(MD5Util.MD5(userInfo.getPassword()))
				.andUserStateEqualTo(1);
			userInfo=userInfoService.selectOneByExample(userInfoExample);
			request.setCharacterEncoding("UTF-8");
			if(userInfo==null){
				model.addAttribute("errorMsg", "用户名密码错误");
				return "login"; 
			}
	    	response.setContentType("text/html");
	        response.setCharacterEncoding("UTF-8");
	        String appid = CommonUtil.getPropertiesParam("wxgzhAppId");
	        String url = "http://" + request.getServerName();
	        String path = request.getContextPath();
	        String getAuthorizeUrl = CommonUtil.getPropertiesParam("getAuthorizeUrl");
	        String redirect_uri = URLEncoder.encode(url + path + "/wxgzh/getOpenId", "UTF-8");
	        return "redirect:"+getAuthorizeUrl + "?redirect_uri=" + redirect_uri +"?userId="+userInfo.getUserInfoId()+
	                "&appid=" + appid + "&response_type=code&scope=snsapi_base&state=1&connect_redirect=1#wechat_redirect"; 
		}catch(Exception e){
			model.addAttribute("errorMsg", "用户名密码错误");
		}
		return "login";
	}
	
    @RequestMapping("/getOpenId")
    public String getOpenId(HttpServletRequest request) throws UnsupportedEncodingException {
        String code = request.getParameter("code");//获取code
        String userId=request.getParameter("userId");
        Map<String, String> params = new HashMap<String, String>();
        params.put("secret", CommonUtil.getPropertiesParam("wxgzhAppsecret"));
        params.put("appid", CommonUtil.getPropertiesParam("wxgzhAppId"));
        params.put("grant_type", "authorization_code");
        params.put("code", code);
        String result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/oauth2/access_token", params);
        JsonNode jn=JsonUtils.fromJson(result);
        if (jn != null) {
            String openid = jn.get("openid").asText();
            System.out.println("得到的openid为:" + openid);
            UserInfo userInfo=new UserInfo();
            userInfo.setUserInfoId(Long.parseLong(userId));
            userInfo.setAttr1(openid);
            userInfoService.updateByPrimaryKeySelective(userInfo);
        }
        return "success";
    }
}
